package org.lifei.gift.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.sun.xml.internal.messaging.saaj.packaging.mime.MessagingException;
import org.lifei.exception.BusinessException;
import org.lifei.exception.LifeiAssert;
import org.lifei.exception.ResponseCode;
import org.lifei.gift.clients.AuthClient;
import org.lifei.gift.domain.Employee;
import org.lifei.gift.domain.LoginUser;
import org.lifei.gift.domain.Tenant;
import org.lifei.gift.domain.TenantMeal;
import org.lifei.gift.dto.TenantDto;
import org.lifei.gift.mapper.EmployeeMapper;
import org.lifei.gift.mapper.TenantMapper;
import org.lifei.gift.service.ITenantService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.lifei.util.AjaxResult;
import org.lifei.util.BaiduAiUtils;
import org.lifei.util.encrypt.MD5;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author lifei
 * @since 2024-03-27
 */
@Service
public class TenantServiceImpl extends ServiceImpl<TenantMapper, Tenant> implements ITenantService {

    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private TenantMapper tenantMapper;
    @Autowired
    private AuthClient authClient;
    @Autowired
    private TenantMealServiceImpl tenantMealService;

//    @Autowired
//    private JavaMailSender javaMailSender;

    @Autowired
    private EmployeeServiceImpl employeeService;
    @Override
    public void settlement(TenantDto dto) {
        //验证当前的店铺,管理员信息是否已经注册过
        Employee admin = dto.getAdmin();
        List<Employee> employees = employeeMapper.selectList(new EntityWrapper<Employee>().eq("username", admin.getUsername()).eq("tel", admin.getTel()));

        if (employees.size()!=0){
            throw new BusinessException("管理员已存在");
        }
        Tenant tenant = dto.getTenant();
        //判断租户名字是否重复
        List<Tenant> tenants = this.selectList(new EntityWrapper<Tenant>().eq("company_name", tenant.getCompanyName()));

        if (tenants.size()!=0){
            throw new BusinessException("租户名字已存在");
        }
        //验证店铺的名字,logo的合法性[涉政,涉爆,涉黄]
        LifeiAssert.isTrue(BaiduAiUtils.textReview(tenant.getCompanyName()), ResponseCode.RESPONSE_CODE_400004);
        //存入数据

        //密码加盐加密
        //密码
        String salt = UUID.randomUUID().toString().replaceAll("-", "");
        String password = MD5.getMD5("lifei" + salt + admin.getPassword() + "qian");
        //远程调用auth保存进login_user
        LoginUser loginUser = new LoginUser();
        loginUser.setUsername(admin.getUsername());
        loginUser.setSalt(salt);
        loginUser.setPassword(password);
        loginUser.setTel(admin.getTel());
        loginUser.setEmail(admin.getEmail());
        loginUser.setType(1);
        AjaxResult ajaxResult = authClient.addOrUpdate(loginUser);
        if (!ajaxResult.isSuccess()){
            //远程调用不成功
            throw new BusinessException(ajaxResult.getMessage());
        }

        Long loginId = Long.parseLong(ajaxResult.getResultObj().toString());
//        Long loginId = 1l;
        //存入t_tenant
        tenant.setState(1);
        tenant.setRegisterTime(new Date());
        tenantMapper.insert(tenant);
        //存入t_emp
        admin.setInputTime(new Date());
        admin.setState(0);
        admin.setSalt(salt);
        admin.setPassword(password);
        employeeMapper.insert(admin);
        //将emp与tenant的id互相保存到对方
        Long adminId = admin.getId();
        tenant.setAdminId(adminId);
        this.insertOrUpdate(tenant);
        Long tenantId = tenant.getId();
        admin.setLoginId(loginId);
        admin.setTenantId(tenantId);
        employeeService.insertOrUpdate(admin);
        //存入t_tenant_meal
        TenantMeal tenantMeal = new TenantMeal();
        tenantMeal.setState(1);
        //一年后的时间
        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.YEAR,1);
        Date instanceTime = instance.getTime();
        tenantMeal.setExpireDate(instanceTime);
        List<TenantMeal> tenantMealList = new ArrayList<>();
        Integer[] meals = dto.getMeals();
        for (Integer meal : meals) {
            tenantMeal.setMealId(Long.parseLong(meal.toString()));
            tenantMealList.add(tenantMeal);
        }
        tenantMealService.insertBatch(tenantMealList);

        //给用户发激活成功邮件
//        try {
//            MimeMessage mimeMessage = javaMailSender.createMimeMessage();
//            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true, "utf-8");
//            //设置发件人
//            helper.setFrom("1821311332@qq.com");
//            //设置收件人
//
//            helper.setTo(admin.getEmail());
//            //设置主题
//            helper.setSubject("审核通过");
//            //设置正文
//            helper.setText("店铺入驻成功");
////        //添加附件
////                helper.addAttachment("1.jpg",new File("E:\\新建文件夹\\新建文本文档.txt"));
////                helper.addAttachment("1",new File("E:\\新建文件夹\\蓉华考试题.zip"));
//
//
//            //javaMailSender.send(mimeMessage);
//            //发邮件实现异步操作
//            Thread thread = new Thread(() -> javaMailSender.send(mimeMessage));
//            thread.start();
//        } catch (MessagingException e) {
//            e.printStackTrace();
//        }


    }
}
